package com.duck.base.oauth.security.handler;


import java.util.Collection;
import java.util.regex.Pattern;

import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.FilterInvocation;

import com.duck.base.oauth.security.properties.UrlRule;

public class DuckUrlValidateHandler implements AccessDecisionVoter<FilterInvocation>{
	
	private UrlRule urlRule;

	public DuckUrlValidateHandler(UrlRule urlRule) {
		super();
		this.urlRule = urlRule;
	}
	
	@Override
	public boolean supports(ConfigAttribute attribute) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		// TODO Auto-generated method stub
		return FilterInvocation.class==clazz;
	}

	@Override
	public int vote(Authentication authentication, FilterInvocation invocation, Collection<ConfigAttribute> attributes) {
		// TODO Auto-generated method stub
		Object pricipal = authentication.getPrincipal();
		String reqUrl = invocation.getRequestUrl();
		if(reqUrl.equals("/instances"))
			return ACCESS_GRANTED;
		String[] reqUrls = reqUrl.split("/");
		if(reqUrls!=null&&reqUrls.length>2) {
			int i=0;
			if(reqUrls[0].equals("")) {
				i=2;
			}else {
				i=1;
			}
			reqUrl = "";
			for(;i<reqUrls.length;i++) {
				reqUrl = reqUrl+"/"+reqUrls[i];
			}
		}
		System.out.println(reqUrl);
		//无需登录白名单校验
		for(String regExUrl:urlRule.getExcluding()) {
			if(Pattern.matches(regExUrl,reqUrl)) {
				return ACCESS_GRANTED;
			}
		}
		
		//用户接口权限校验
		if(authentication.isAuthenticated() && pricipal!=null && pricipal instanceof UserDetails) {			
			//需要登录的白名单校验
			for(String regExUrl:urlRule.getIncluding()) {
				if(Pattern.matches(regExUrl,reqUrl)) {
					return ACCESS_GRANTED;
				}
			}
			
			//菜单下自定义接口权限校验
			
		}
				
		
		return ACCESS_DENIED;
	}

}
